package com.we.flink.userlabelplatform.tag;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import com.we.flink.userlabelplatform.table.TableVerifyUserLineExt;

public class TagVerifyUserLineExt {
    public String user_key;
    public float last_increase_quota_lift_amount;
    public long last_increase_quota_expired_time;
    public int update_time;

    public TagVerifyUserLineExt() {}

    public TagVerifyUserLineExt(
            String user_key,
            float last_increase_quota_lift_amount,
            long last_increase_quota_expired_time,
            int update_time) {
        this.user_key = user_key;
        this.last_increase_quota_lift_amount = last_increase_quota_lift_amount;
        this.last_increase_quota_expired_time = last_increase_quota_expired_time;
        this.update_time = update_time;
    }

    public static TagVerifyUserLineExt init(String user_key) {
        return new TagVerifyUserLineExt(user_key, 0, 0, 0);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableVerifyUserLineExt.QUERYSQL);
        DataStream<Tuple2<Boolean, TableVerifyUserLineExt>> inputStream =
                tableEnv.toRetractStream(tableRes, TableVerifyUserLineExt.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableVerifyUserLineExt>>() {
                                    @Override
                                    public boolean filter(
                                            Tuple2<Boolean, TableVerifyUserLineExt> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagVerifyUserLineExt-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableVerifyUserLineExt>, String>() {
                                    @Override
                                    public String getKey(
                                            Tuple2<Boolean, TableVerifyUserLineExt> value)
                                            throws Exception {
                                        return value.f1.getUser_key();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableVerifyUserLineExt>, String>() {
                                    ValueState<TagVerifyUserLineExt> verifyUserLineExtVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        verifyUserLineExtVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TagVerifyUserLineExt>(
                                                                        "verifyUserLineExtVState",
                                                                        TagVerifyUserLineExt
                                                                                .class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableVerifyUserLineExt> value,
                                            Collector<String> out)
                                            throws Exception {
                                        String user_key = value.f1.getUser_key();
                                        float lift_amount = value.f1.getLift_amount();
                                        long tmp_expire_time =
                                                (Long.parseLong(value.f1.getTmp_expire_time())
                                                        / 1000);
                                        int update_time =
                                                (int) (value.f1.getUpdate_time().getTime() / 1000);
                                        JSONObject jsonObject = new JSONObject();
                                        jsonObject.put("user_key", user_key);

                                        TagVerifyUserLineExt tmpState =
                                                verifyUserLineExtVState.value();
                                        TagVerifyUserLineExt curState =
                                                tmpState == null
                                                        ? TagVerifyUserLineExt.init(user_key)
                                                        : tmpState;

                                        if (update_time > curState.getUpdate_time()) {
                                            if (lift_amount
                                                    != curState
                                                            .getLast_increase_quota_lift_amount()) {
                                                curState.last_increase_quota_lift_amount =
                                                        lift_amount;
                                                jsonObject.put(
                                                        "last_increase_quota_lift_amount",
                                                        lift_amount);
                                            }
                                            if (tmp_expire_time
                                                    != curState
                                                            .getLast_increase_quota_expired_time()) {
                                                curState.last_increase_quota_expired_time =
                                                        tmp_expire_time;
                                                jsonObject.put(
                                                        "last_increase_quota_expired_time",
                                                        tmp_expire_time);
                                            }
                                            curState.update_time = update_time;
                                            verifyUserLineExtVState.update(curState);
                                        }

                                        if (jsonObject.size() > 1) {
                                            out.collect(jsonObject.toString());
                                        }
                                    }
                                });
        return out;
    }

    public String getUser_key() {
        return user_key;
    }

    public float getLast_increase_quota_lift_amount() {
        return last_increase_quota_lift_amount;
    }

    public long getLast_increase_quota_expired_time() {
        return last_increase_quota_expired_time;
    }

    public int getUpdate_time() {
        return update_time;
    }
}
